<template>
  <!-- 需求列表 -->
  <div>
        <div style="display: flex; justify-content: flex-end">
          <el-select
            v-model="value"
            placeholder="请选择"
            @change="changeSelect"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            placeholder="请输入需求资源名称"
            v-model="name"
            class="input-with-select"
            style="width: 300px"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchBtn"
            ></el-button>
          </el-input>
        </div>

        <el-table
          :data="tableData"
          border
          style="width: 100%; margin: 10px 0"
          height="560"
        >
          <el-table-column
            fixed
            prop="dataName"
            label="需求资源名称"
            width="200"
            align="center"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="descri"
            label="需求描述"
            width="180"
            align="center"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="sqr"
            label="申请人"
            width="120"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="申请时间"
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              {{ scope.row.createTime | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop="spzt"
            label="审批状态"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.spzt === 0">待数据局初审</span>
              <span v-else-if="scope.row.spzt === 1">初审通过，待数据源部门审核 </span>
              <span v-else-if="scope.row.spzt === 2">初审通过且已有数据编目</span>
              <span v-else-if="scope.row.spzt === 3">初审退回</span>
              <span v-else-if="scope.row.spzt === 4">待数据局复审</span>
              <span v-else-if="scope.row.spzt === 5">数据源部门退回</span>
              <span v-else-if="scope.row.spzt === 6">数据局复审退回</span>
              <span v-else-if="scope.row.spzt === 7">复审通过</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="spr"
            label="审核人"
            width="120"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="updateTime"
            label="审核时间"
            width="200"
            align="center"
          >
            <template slot-scope="scope" >
              <span v-if="scope.row.updateTime && scope.row.updateTime !== null">
                  {{ scope.row.updateTime  | formatDate }}
              </span>
              <span v-else> 暂无审批时间 </span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="120">
            <template slot-scope="scope">
              <el-button @click="handleClickDetail(scope.row)" type="text" size="small">查看</el-button>
              <el-button type="text" size="small" @click="cxBtn(scope.row)">撤销</el-button>
              <el-button type="text" size="small" @click="cxtjBtn(scope.row)" v-if="scope.row.spzt === 3">重新提交</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex; justify-content: flex-end">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="prev, pager, next, sizes, jumper"
            :total="totalNum"
          >
          </el-pagination>
        </div>
<!--        申请详情-->
    <el-dialog
      :visible.sync="dialogVisible"
      width="80%"
     >
      <el-descriptions title="申请详情">
        <el-descriptions-item label="需求资源名称">{{detailList.dataName}}</el-descriptions-item>
        <el-descriptions-item label="服务方式">
          {{detailList.type === 0
          ? '数据库'
          : detailList.type === 1
            ? 'API 接口'
            : detailList.type === 2
              ? '文件'
              : '未知类型'}}
        </el-descriptions-item>
        <el-descriptions-item label="数据项">{{ detailList.dataItem }}</el-descriptions-item>
        <el-descriptions-item label="资源覆盖范围">{{detailList.resourceRange}}</el-descriptions-item>
        <el-descriptions-item label="申请人名称">{{detailList.sqr}}</el-descriptions-item>
        <el-descriptions-item label="申请人手机号">{{detailList.phone}}</el-descriptions-item>
        <el-descriptions-item label="申请人邮箱">{{detailList.email}}</el-descriptions-item>
        <el-descriptions-item label="数据需求部门">{{detailList.appDept}}</el-descriptions-item>
        <el-descriptions-item label="需求描述">{{detailList.descri}}</el-descriptions-item>
        <el-descriptions-item label="使用起始时间">{{detailList.startTime | formatDate}}</el-descriptions-item>
        <el-descriptions-item label="使用结束时间">{{detailList.endTime | formatDate}}</el-descriptions-item>
        <el-descriptions-item label="应用场景">{{detailList.appScene}}</el-descriptions-item>
<!--        <el-descriptions-item label="出参">{{detailList.inputArg ? detailList.inputArg : '无'}}</el-descriptions-item>-->
<!--        <el-descriptions-item label="入参">{{detailList.outputArg ? detailList.outputArg : '无'}}</el-descriptions-item>-->
        <el-descriptions-item label="数据所属部门">{{detailList.dataDept}}</el-descriptions-item>
        <el-descriptions-item label="文件名称">
          <span :class="{ 'file-exists': detailList.file }" @click="handleDownload(detailList.file)">
      {{ detailList.file ? detailList.file.fileName : '暂无' }}
    </span>
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
<!--    重新提交弹窗-->
    <el-dialog title="重新提交" :visible.sync="dialogFormVisibleCxtj">
      <div slot="footer" class="dialog-footer">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="需求资源名称" prop="dataName">
            <el-input v-model="ruleForm.dataName" oninput="value=value.replace(/^((?!^[\u4e00-\u9fa5_a-zA-Z0-9_\s]+$).)*/g,'')"></el-input>
          </el-form-item>
          <el-form-item label="服务方式" prop="type">
            <el-radio
              v-for="(item, index) in tabsList"
              :key="index"
              v-model="ruleForm.type"
              :label="index"
              style="margin-top: 10px"
            >{{ item }}</el-radio
            >
          </el-form-item>

<!--          <div v-if="ruleForm.type == 1">-->
<!--            <el-form-item label="出参" prop="outputArg">-->
<!--              <el-input-->
<!--                v-model="ruleForm.outputArg"-->
<!--                placeholder="服务API时填写，请求参数和返回..."-->
<!--              ></el-input>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="入参" prop="inputArg">-->
<!--              <el-input-->
<!--                v-model="ruleForm.inputArg"-->
<!--                placeholder="服务API时填写，请求参数和返回..."-->
<!--              ></el-input>-->
<!--            </el-form-item>-->
<!--          </div>-->
          <div>
            <el-form-item label="数据项目" prop="dataItem">
              <el-input
                v-model="ruleForm.dataItem"
                placeholder="文件下载和其他类型时填写..."
              ></el-input>
            </el-form-item>
          </div>
          <el-form-item label="资源覆盖范围" prop="resourceRange">
            <el-input
              type="textarea"
              resize="none"
              :autosize="{ minRows: 3, maxRows: 4 }"
              placeholder="数据资源的地域范围、时间范围"
              v-model="ruleForm.resourceRange"
              maxlength="50"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <el-form-item label="申请人">
            <el-input
              disabled
              v-model="parrment.username"
              placeholder="法人单位名称/个人姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="审批人" prop="spr">
            <el-select v-model="ruleForm.spr" placeholder="请选择审批人">
              <el-option
                v-for="item in sprlist"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>

            <!--        <el-input-->
            <!--          readonly-->
            <!--          class="deptInp"-->
            <!--          v-model="ruleForm.spr"-->
            <!--          placeholder="审批人"-->
            <!--          oninput="value=value.replace(/^((?!^[\u4e00-\u9fa5_a-zA-Z0-9_\s]+$).)*/g,'')"-->
            <!--        ></el-input>-->
            <!--        <div class="deptBtn">-->
            <!--          <el-button @click="chooseSpr()" type="text" size="medium">-->
            <!--            选择审批人-->
            <!--          </el-button>-->
            <!--        </div>-->
          </el-form-item>
          <div style="display: flex">
            <el-form-item prop="phone" label="联系电话">
              <el-input v-model="ruleForm.phone" placeholder="联系电话"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="联系邮箱">
              <el-input v-model="ruleForm.email" placeholder="联系邮箱"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="需求描述" prop="descri">
            <el-input
              resize="none"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 4 }"
              placeholder="请输入需求描述"
              v-model="ruleForm.descri"
              maxlength="50"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <div style="display: flex">
            <el-form-item prop="startTime" label="使用起始时间">
              <el-date-picker
                :editable="false"
                type="date"
                placeholder="选择日期"
                v-model="ruleForm.startTime"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item prop="endTime" label="使用结束时间">
              <el-date-picker
                :editable="false"
                type="date"
                placeholder="选择日期"
                v-model="ruleForm.endTime"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </div>
          <el-form-item label="应用场景" prop="appScene">
            <el-input
              resize="none"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 4 }"
              placeholder="请输入应用场景"
              v-model="ruleForm.appScene"
              maxlength="50"
              show-word-limit
            >
            </el-input>
          </el-form-item>
<!--          <el-form-item label="上传文件">-->
<!--            <el-upload-->
<!--              class="upload-demo"-->
<!--              :action="xhDomain + '/api/interact/add'"-->
<!--              :on-preview="handlePreview"-->
<!--              :headers="headers"-->
<!--              :on-remove="handleRemove"-->
<!--              :on-success="handleSuccess"-->
<!--              :before-remove="beforeRemove"-->
<!--              :limit="1"-->
<!--              :on-exceed="handleExceed"-->
<!--              :file-list="fileList"-->
<!--              :show-file-list="false"-->
<!--              :before-upload="beforeUpload"-->
<!--              :on-progress="handleProgress"-->
<!--              :on-error="handleError"-->
<!--            >-->
<!--              <el-button size="small" type="primary">点击上传</el-button>-->
<!--              &lt;!&ndash; <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> &ndash;&gt;-->
<!--            </el-upload>-->
<!--          </el-form-item>-->

          <el-form-item>
            <el-button type="primary" @click="cxspBtn('ruleForm')"
            >确定</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>

      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  xqlist,
  xqlistDetail,
  cxDeletebyid,
  getdept,
  getspr,
  getdataDeptSpyj,
  gecxtj
} from "@/utils/httpUtils";
import Cookies from "js-cookie";
import {getupdatas} from "../../../utils/httpUtils";
import {
  isvalidPhone,
  validEmail,
} from "@/utils/validate.js";
export default {
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const isvalidEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!validEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    const startTimeValid = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择起始时间'))
      } else {
        if (!this.ruleForm.endTime) {
          callback()
        } else if(new Date(value).getTime() < new Date(this.ruleForm.endTime).getTime()){
          callback()
        } else {
          callback(new Error('起始时间应早于结束时间'))
        }
      }
    }
    const endTimeValid = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择结束时间'))
      } else {
        if (!this.ruleForm.startTime) {
          callback()
        } else if(new Date(value).getTime() > new Date(this.ruleForm.startTime).getTime()){
          callback()
        } else {
          callback(new Error('结束时间应晚于起始时间'))
        }
      }
    }
    return {
      sprlist:[],
      parrment: Cookies.get("user")
        ? JSON.parse(Cookies.get("user"))
        : {},
      tabsList: ["数据库", "服务API", "文件下载"],
      ruleForm: {
        dataName: "",//名称
        type: 0,//服务方式
        // dataDept: "",//所属部门
        // outputArg: "",//出参
        // inputArg: "",//入参
        dataItem: "",//数据项目
        resourceRange: "",//资源覆盖范围
        // sqr: "",//申请人
        spr: "",//审批人
        phone: "",//手机号
        email: "",//邮箱
        descri: "",//需求描述
        startTime: "",//使用起始时间
        endTime: "",//使用结束时间
        appScene: "",//应用场景
        code: "",//校验码
      },
      rules: {
        dataName: [
          { required: true, message: "请输入需求资源名称", trigger: "blur" },
          { min: 2, max: 15, message: "长度在 2 到 15 个字符", trigger: "blur" }
        ],
        dataDept: [
          { required: true, message: "请选择归属部门", trigger: "change" },
          // { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" }
        ],
        dataItem: [
          { required: true, message: "请输入数据项", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        resourceRange: [
          { required: true, message: "请输入资源覆盖范围", trigger: "blur" },
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        email: [
          { required: true, trigger: 'blur', validator: isvalidEmail }
        ],
        appScene: [
          { required: true,  message: "请输入应用场景", trigger: "blur" },
        ],
        // sqr: [
        //   { required: true, message: "请输入申请人", trigger: "blur" },
        //   // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        // ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
        startTime: [
          { type: "date", required: true, trigger: "change", validator: startTimeValid },
        ],
        endTime: [
          { type: "date", required: true, trigger: "change", validator: endTimeValid },
        ],
      },
      dialogFormVisibleCxtj: false,
      dialogVisible: false,
      show: false,
      value: "",
      options: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "0",
          label: "待数据局初审",
        },
        {
          value: "1",
          label: "初审通过，待数据源部门审核",
        },
        {
          value: "2",
          label: "初审通过且已有数据编目",
        },
        {
          value: "3",
          label: "初审退回",
        },
        {
          value: "4",
          label: "待数据局复审",
        },
        {
          value: "5",
          label: "数据源部门退回",
        },
        {
          value: "6",
          label: "数据局复审退回",
        },
        {
          value: "7",
          label: "复审通过",
        },
      ],
      name: "",
      tableData: [],
      activeName: "dataResource",
      currentPage: 1,
      pageNo: 1,
      pageSize: 10,
      status: "",
      totalNum: 0,
      detailsList: {
        resourceName: "",
        resourceType: "",
        applyInstitution: "",
        createUser: "",
        type: "",
        updateTime: "",
        description: "",
        createTime: "",
        updateUser: "",
        auditStatus: "",
      },
      updateCycleList: [],
      shareTypeList: [],
      ShareModeList: [],
      resourceType: 0,
      detailList:{}
    };
  },
  mounted() {
    this.initData()
    this.getsprFn()
  },
  //   处理1703592547000 时间格式
  filters: {
    formatDate(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
  methods: {
    handleDownload(file){
      console.log(file,'file');
      //   文件下载
      this.$axios({
        url: xhDomain + `/api/interact/download/${file.fileId}`,
        method: 'post',
        responseType: 'blob', // 确保响应是二进制数据
        headers: {
          'Content-Type': 'application/json',
          "Authorization": JSON.parse(localStorage.getItem('token'))
        },
      }).then((res) => {
        console.log(res, 'res')
        const blob = new Blob([res.data], { type: 'application/octet-stream' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = file.fileName; // 设置下载文件的文件名，可以根据需要修改
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        }, 100);
      }).catch((err) => {
        console.log(err,"err")
        // responseType: 'blob' 这个类型获取报错提示
        if (err.response.data.type === 'application/json') {
          const fileReader = new FileReader();
          fileReader.readAsText(err.response.data, 'utf-8');
          fileReader.onload = function () {
            const result = JSON.parse(fileReader.result);
            console.log(result, 'result');
            this.$message.error(result.message);
          }.bind(this); // Bind `this` to the onload function
          return;
        }

        const content = err.data
        const blob = new Blob([content], {
          type: "application/octet-stream"
        }) //构造一个blob对象来处理数据
        // this.$message.error(err.response.message)
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    cxspBtn(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formattedRuleForm = {
            ...this.ruleForm,
            dataDept:this.selectedLabel,
            appDept:this.selectedLabelSq,
          };
          getupdatas(formattedRuleForm).then(res=>{
            console.log(res,"重新提交修改")
            this.$message({
              message: res,
              type: "success",
            });
            this.dialogFormVisibleCxtj = false
          })
        }else {
          console.log("error submit!!");
          return false;
        }
      })
    },
    getsprFn(){
      getspr().then(res=>{
        console.log(res,"审批人")
        this.sprlist = res.map(item => ({
          value: item.nickName,
          label: item.nickName
        }));
      })
    },


    cxtjBtn(row){
      this.dialogFormVisibleCxtj = true
      gecxtj({id:row.id}).then(res=>{
        console.log(res,'回显')
        this.ruleForm = res
      })
    },
    cxBtn(row){
      this.$confirm('是否撤回?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cxDeletebyid({id:row.id}).then(res=>{
          console.log(res,"撤销123")
          if(res.code == 200){
            this.$message({
              type: 'success',
              message: '撤回成功!'
            });
            this.initData()
          }
        }).catch((err)=>{
          console.log(err,"err")
          this.$message({
            type: 'error',
            message: err.response.data.message
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      })

    },
    handleClickDetail(row){
      console.log(row.id, "row")
      xqlistDetail({id:row.id}).then(res=>{
        console.log(res,'详情')
        this.dialogVisible = true
        this.detailList = res
      })
    },
    searchBtn() {
        this.initData();
    },

    changeSelect(val) {
      console.log(val, "val");
      this.status = val;
      this.initData();
    },
    // 初始化数据
    initData() {
      xqlist({
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        dataName: this.name,
        spzt:this.value,
      }).then((res) => {
        console.log(res, "我的申请，数据资源");
        this.tableData = res.content;
        this.totalNum = res.totalElements;
        this.name = "";
      });
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNo = val;
      this.initData();
    },
  },
};
</script>
<style  scoped>
.listToggle {
  padding: 13px 20px;
}

.listToggle.backBtn {
  border-bottom: 4px solid #198ef8;
}
.file-exists {
  color: #409eff;
  cursor: pointer;
}
</style>


